<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/24
 * Time: 16:45
 */

namespace osc\admin\controller;


use osc\common\controller\AdminBase;
use think\Db;
use think\Request;

class Agent extends AdminBase
{

    protected function _initialize(){
        parent::_initialize();
        $this->assign('breadcrumb1','代理');
        $this->assign('breadcrumb2','区域管理');
    }

    /**
     * 代理区域列表
     * @return mixed
     */
    public function region(){
        $param = $this->request->param();
        $map = [];
        if(!empty($param['username'])){
            $map['username'] = $param['username'];
        }
        if(!empty($param['id6'])){
            $map['id6'] = $param['id6'];
        }
        $list = Db::name('agent_area')
            ->where($map)
            ->paginate(10,false, [
                'query' => Request::instance()->param(),//不丢失已存在的url参数
            ]);
        $page = $list->render();
        $this->assign('list',$list);
        $this->assign('page',$page);
        return $this->fetch();
    }

    /**
     * 新增代理区域
     * @return array
     */
    public function add(){
        if($this->request->isPost()){
            $data = $this->request->post();

            if(!$data['username'] || !$data['id6']){
                $this->error('添加不能为空');
            }

            $user = Db::name('member')->where('username',$data['username'])->find();
            if(!$user){ $this->error('用户不存在'); }

            $open = Db::name('agent_area')->where('id6',$data['id6'])->find();
            if($open){ $this->error('身份证前6位不可重复添加'); }

            $res = Db::name('agent_area')->insert($data);

            if($res){
                $this->success('新增成功');
            }
            $this->error('新增失败');
        }else{
            $this->error('提交错误');
        }
    }


    /**
     * 删除代理区域
     */
    public function del(){
        $param = $this->request->param();
        $res = Db::name('agent_area')->where('id',$param['id'])->delete();
        if($res){
            storage_user_action(UID,admin('username'),config('BACKEND_USER'),'删除了代理区域-'.$param['id']);
            $this->success('删除成功！');
        }else{
            $this->error('删除失败！');
        }
    }

}